package edu.washington.vaccine.ui;

import java.util.ArrayList;
import java.util.List;

import edu.washington.vaccine.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import edu.washington.vaccine.backend.Patient;
import edu.washington.vaccine.backend.Vaccine;
import edu.washington.vaccine.backend.VaccineDB;
import edu.washington.vaccine.backend.VaccineLocalHelper;

/*
 * Manages sending data to either the online or
 * local database. Handles sending data from the
 * add patient and edit patient screens
 */
public class SendDataListener implements OnClickListener {
	private Activity activity;
	private boolean sendToDb;
	private Class<?> cls;
	private String label;
	private VaccineDB db = VaccineDB.getInstance();

	public SendDataListener(Activity activity, boolean sendToDb, Class<?> cls, String label) {
		this.activity = activity;
		this.sendToDb = sendToDb;
		this.cls = cls;
		this.label = label;
	}

	public void onClick(View v) {
		TextView box = (TextView) activity.findViewById(R.id.idNumber);
		String idNumber = box.getText().toString().trim();
		if (idNumber.equals("")) idNumber = "0";
		final String finalId = idNumber;
		box = (TextView) activity.findViewById(R.id.firstName);
		String firstName = box.getText().toString().trim();
		if (!firstName.equals("")) {
			firstName = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
		}

		box = (TextView) activity.findViewById(R.id.lastName);
		String lastName = box.getText().toString().trim();
		if (!lastName.equals("")) {
			lastName = lastName.substring(0,1).toUpperCase() + lastName.substring(1);
		}

		DatePicker d = (DatePicker) activity.findViewById(R.id.birthdate);
		String birthdate = "";
		int month = d.getMonth() + 1;
		int day = d.getDayOfMonth();
		int year = d.getYear();

		if (month < 10)
			birthdate = "0";
		birthdate += month + "-";

		if (day < 10)
			birthdate += "0";
		birthdate += day + "-" + year;
		
		box = (TextView) activity.findViewById(R.id.birthplace);
		String birthplace = box.getText().toString();

		box = (TextView) activity.findViewById(R.id.motherName);
		String mother = box.getText().toString().trim();

		box = (TextView) activity.findViewById(R.id.fatherName);
		String father = box.getText().toString().trim();

		//		box = (TextView) activity.findViewById(R.id.vaccinesReceived);
		//		String vaccines = box.getText().toString().trim();

		final Patient p = new Patient(Integer.parseInt(idNumber), lastName, firstName,
				birthdate, birthplace, father, mother, "", "", "");

		if (!label.equals("results")){

			AlertDialog.Builder builder = new AlertDialog.Builder(activity.getParent().getParent());
			builder.setMessage("ID Number: " + p.id + "\nFirst Name: " + p.fname +
					"\nLast Name: " + p.lname + "\nBirthplace: " + p.location +
					"\nBirthdate: " + p.dob + "\nMother's Name: " + p.mother +
					"\nFather's Name: " + p.father)
					.setCancelable(false)
					.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							continueSending(finalId, p);
						}
					})
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alert = builder.create();
			alert.show();
		} else {
			continueSending(finalId, p);
		}
	} 

	public void continueSending(String idNumber, Patient p) {
		if (activity instanceof EditPatientActivity) {
			if (db.isOnlineMode()) {
				p.editdate = db.getEditDate("" + p.id);
				db.editPatient(p);
				sendVaccine(true, p);
			} else {
				VaccineLocalHelper.getInstance(activity).editPatient(p);
				sendVaccine(false, p);
			}
		} else if (sendToDb) {
			if (idNumber.equals("0") || Integer.parseInt(idNumber) < 1) {
				Toast.makeText(activity, "Invalid ID number", Toast.LENGTH_SHORT).show();
				return;
			} else {
				if (db.isOnlineMode()) {
					db.addPatient(p);
					if (activity instanceof AddPatientActivity) {
						sendVaccine(true, p);
					}
				} else {
					VaccineLocalHelper.getInstance(activity).addPatient(p);
					if (activity instanceof AddPatientActivity) {
						sendVaccine(false, p);
					}
				}
			}
		}

		Intent i = new Intent(activity, cls);
		i.putExtra("patient", p); 
		//		VaccineActivity parentActivity = (VaccineActivity)activity.getParent();
		//		parentActivity.replaceContentView(label, i);
		FirstGroup.group.addChildActivity(label, i);
	}
	
	private void sendVaccine(boolean isOnline, Patient p) {
		VaccineLocalHelper localDB = VaccineLocalHelper.getInstance(activity);
		final List<Vaccine> pArray = new ArrayList<Vaccine>();
		Cursor cursor = localDB.getReadableDatabase().rawQuery("SELECT * FROM Vaccines", new String [] {});
		activity.startManagingCursor(cursor);
		while (cursor.moveToNext()) {
			int vid = cursor.getInt(0);
			String vname = cursor.getString(1);
			String vdesc = cursor.getString(2);
			String vschedule = cursor.getString(3);
			pArray.add(new Vaccine(vid, vname, vdesc, vschedule));
		}
		for(Vaccine v : pArray) {
			TextView text = (TextView) activity.findViewById(v.id);
			if(!(text == null || text.getText() == null || text.getText().equals(""))) {
				String dateText = ("" + text.getText()).trim();
				if (isOnline) {
					db.addVaccineFromOffline("" + p.id, "" + v.id, dateText);
				} else {
					localDB.addVaccineWithDate("" + p.id, "" + v.id, dateText);
				}
			}
		}
		cursor.close();
	}
}
